package com.qiqidream.admin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiqidream.admin.security.entity.SecurityUser;
import com.qiqidream.admin.system.mapper.RoleMapper;
import com.qiqidream.admin.system.mapper.UserMapper;
import com.qiqidream.admin.system.model.entity.Role;
import com.qiqidream.admin.system.model.entity.User;
import com.qiqidream.admin.system.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义userDetailsService - 认证用户详情
 * @author QiQiDream
 * @since 2019/11/18 10:53
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUser(String userName) {
        // 从数据库中取出用户信息
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, userName));
        // 判断用户是否存在
        if (ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException("用户名不存在！");
        }

        List<Long> roleIds = ObjectUtils.isEmpty(user.getAuthJson())?new ArrayList<>():user.getAuthJson().getRole();

        if (ObjectUtils.isEmpty(roleIds)) {
            return ObjectUtils.isEmpty(user) ? null : new SecurityUser(user,new ArrayList<>());
        }

        List<Role> roles = roleMapper.selectList(new LambdaQueryWrapper<Role>().in(Role::getId, roleIds));


        return ObjectUtils.isEmpty(user) ? null : new SecurityUser(user,roles);
    }

}
